// 规定 某一类型的 公共函数超过3个后 单独写一个文件
import { getIntl } from 'umi';
// import { v4 as uuidv4 } from 'uuid';
// import { uuid } from 'uuidv4';
import moment from 'moment';
import CryptoJS from 'crypto-js';

/**
 * 从本地 public/config中获取json文件
 * @param name json文件名
 * @returns 返回json格式数据
 */
export async function getJson(name: string, path: string = '/'): Promise<any> {
  const res = await fetch(`${path}config/${name}.json`);
  const data = await res.json();
  return data;
}

/**
 * 国际化语法糖 简化 intl.formatMessage 的用法
 * @param id
 * @param defaultMessage
 * @param namedParams
 * @returns
 */
export function intl(id: string, defaultMessage: string | undefined, namedParams?: any): string {
  // 使用全局的
  return getIntl().formatMessage({ id, defaultMessage }, namedParams);
}
/**
 * 国际化 列标题，支持所有 带title类型的
 * 最典型的用法，是用在table的columns中
 * @param intlPrefix 前缀
 * @param items 一般为 column 数组
 * @returns any[]
 * 用法：
 * <Table
 *   columns={ intlItems('test', columns)}
 */
export function intlItems(intlPrefix: string, items: any[], key: string = 'dataIndex'): any[] {
  const newCols = items.map((item: any) => {
    return {
      ...item,
      title: item.title ? intl(`${intlPrefix}.${item[key]}`, item.title) : item.title,
    };
  });
  return newCols;
}

/**
 * 列表转树结构
 * 参考：https://www.cnblogs.com/shb190802/p/13647203.html 有4种方法
 * 注意：必须要有 id pid 字段
 * @param list 后台的数据 []
 * @param opt 选项
 * @returns
 */
export async function list2Tree(
  list: any[],
  opt?: {
    id?: string; // id
    pid?: string; // 父级ID
    pValue?: string; // 顶级节点值 默认  ""
    callback?: (item: any) => boolean; // Promise<API.CurrentUser | undefined>
  },
) {
  const itemObj: any = {};
  let id: string = 'id';
  let pid: string = 'pid';
  let pValue: string = '';
  if (opt) {
    id = opt.id || 'id';
    pid = opt.pid || 'pid';
    pValue = opt.pValue || '';
  }
  list.forEach((item: any) => {
    if (opt && opt.callback) {
      if (opt.callback(item)) {
        itemObj[item[id]] = item;
      }
    } else {
      itemObj[item[id]] = item;
    }
  });
  return list.filter((item: any) => {
    if (item[pid] && item[pid] !== pValue) {
      const obj = itemObj[item[pid]];
      if (obj) {
        if (!obj.children) {
          obj.children = [];
        }
        obj.children.push(item);
      }
      return false;
    }
    return true;
  });
}

/**
 * 树型结构 过滤检索
 * @param treeData
 * @param searchText
 * @param opt.cols 搜索的列，不传全部（但效率低），建议传 opt.children 默认 children
 * @returns 返回一个树型结构
 */
export function filterTreeData(
  treeData: any[],
  searchText: any,
  opt?: {
    cols: any[];
    children?: string;
  },
): any[] {
  const getFullText = (item: any, cols: any): string => {
    let keys: any[] = Object.keys(item);
    if (cols && cols.length > 0) {
      keys = cols;
    }
    let str: string = '';
    keys.forEach((key: string) => {
      str += item[key];
    });
    return str;
  };
  if (!treeData || treeData.length === 0) {
    return [];
  }
  let children = 'children';
  if (opt) {
    children = opt.children || 'children';
  }
  const array: any[] = [];
  treeData.forEach((item: any) => {
    let match: boolean = false;
    const fullText = getFullText(item, opt?.cols);
    match = match || fullText.includes(searchText);
    if (filterTreeData(item[children], searchText, opt).length > 0 || match) {
      array.push({
        ...item,
        children: filterTreeData(item[children], searchText, opt),
      });
    }
  });
  return array;
}

/*
对本地数据搜索
treeData 数据源
searchText 搜索的值
opt.cols 根据那些 键名 进行过滤
*/
export function searchFilterData(
  treeData: any[],
  searchText: any,
  opt?: {
    cols: any[];
  },
): any[] {
  const getFullText = (item: any, cols: any): string => {
    let keys: any[] = Object.keys(item);
    if (cols && cols.length > 0) {
      keys = cols;
    }
    let str: string = '';
    keys.forEach((key: string) => {
      str += item[key];
    });
    return str;
  };
  if (!treeData || treeData.length === 0) {
    return [];
  }
  const array: any[] = [];
  treeData.forEach((item: any) => {
    let match: boolean = false;
    const fullText = getFullText(item, opt?.cols);
    match = match || fullText.includes(searchText);
    if (match) {
      array.push({
        ...item,
      });
    }
  });
  return array;
}

export function formatterTime(val: any): string {
  if (!val) return '';
  const m = moment(val);
  return m.isValid() ? m.format('YYYY-MM-DD HH:mm:ss') : '';
}

// 获取是否是IE内核浏览器
export const isIEBrowser = () => {
  const ua = window.navigator.userAgent;

  // MSIE内核
  const msie = ua.indexOf('MSIE ');
  if (msie > 0) {
    return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  }

  // Trident(又称为MSHTML) 代表：Internet Explorer
  const trident = ua.indexOf('Trident/');
  if (trident > 0) {
    const rv = ua.indexOf('rv:');
    return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  }

  return false;
};
/**
 * webpack时把双规划线变为一个
 * @param fileName
 * @returns
 */
export function replaceFileName(fileName: string) {
  return fileName.replace('___', '_').replace('__', '_');
}




/**
 * mySecretKey 密钥
 */
const mySecretKey = "WeLoveYouDataSum";
/**
 * DES 加密
 * content:明文, secretKey:密钥
 */
export function encryptByDES(content: any) {
  const key = CryptoJS.enc.Utf8.parse(mySecretKey);
  const srcs = CryptoJS.enc.Utf8.parse(content);
  const encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.toString();
}

/**
 * DES 解密
 * ciphertext:密文, secretKey:密钥
 */
export function decryptByDES(ciphertext: any) {
  const key = CryptoJS.enc.Utf8.parse(mySecretKey);
  const decrypt = CryptoJS.AES.decrypt(ciphertext, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}

// 获取月份
export const getMomentMonth = (timeData: any) => {
  const date = moment(timeData); // 获取时间
  const month = date.month() + 1; // 获取月份
  return month;
}




// 获取月份
export const getMomentMonthSjnd = (timeDataS: any, timeDataE: any) => {

  let moothStart = 0;
  let moothEND = 0;
  let isYear = true;
  let moothStr = '';
  let yearStr = '';
  yearStr = `${moment(timeDataS).year()}`;
  moothStart = moment(timeDataS).month() + 1;
  moothEND = moment(timeDataE).month() + 1;

  isYear = moothStart == 1 && moothEND == 12;
  moothStr = isYear ? `${yearStr}年度` : `${yearStr}年${moothStart}-${moothEND}月`;

  return moothStr;
}




export const getWindowsMapsList = (tempDataID: any) => {
  const tempData = window.main.mainObject.getIndependentWindowsMaps();
  const isContained = tempData.some((item: string) => item.includes(tempDataID));
  console.log(isContained, tempData, '@@@');
  return isContained;
}



function removeFromLocalStorage(delKeys: string[], delData: string[]) {
  // 遍历键，找到匹配模糊条件的键，然后移除
  delKeys.forEach((key: any) => {
    delData.forEach((item: any) => {
      if (key.includes(item)) {
        console.log('删除 @@@', key);
        window.localStorage.removeItem(key);
      }
    });
  });
}

// 删除本地存储信息
export const removeLocalStorageItem = (localName: string) => {
  // 获取本地存储中所有的键
  const allKeys = Object.keys(window.localStorage);
  let delKeys: string[] = [];
  allKeys.forEach((key: any) => {
    if (key.includes(localName)) {
      delKeys.push(key);
    }
  });
  const delData = [
    `审定财务-资产减值准备情况表-${localName}`,
    `fsNameData-${localName}`, `dbNameData-${localName}`,
    // `selectDefaultSsph_${localName}`, `selectDefaultTool_${localName}`,
    // `selectFinancialTool_${localName}`, `selectOpeningTool_${localName}`,
    // `试算平衡_资产减值准备情况表_${localName}`,
    `_${localName}`
  ];
  removeFromLocalStorage(delKeys, delData);
};